package com.horqian.api.oktoberfest

import android.content.Context
import android.content.SharedPreferences

object SPUtils {

    private val spName = "spMP"

    fun putValue(context: Context, key: String?, value: Any?) {
        val sp: SharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        val edit = sp.edit()
        when (value) {
            is Boolean -> {
                edit.putBoolean(key, (value as Boolean?)!!)
            }
            is Float -> {
                edit.putFloat(key, (value as Float?)!!)
            }
            is Int -> {
                edit.putInt(key, (value as Int?)!!)
            }
            is Long -> {
                edit.putLong(key, (value as Long?)!!)
            }
            is String -> {
                edit.putString(key, value as String?)
            }
        }
        edit.apply()
    }

    fun getValue(context: Context, key: String?, defValue: Any?): Any? {
        val sp: SharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        when (defValue) {
            is Boolean -> {
                return sp.getBoolean(key, (defValue as Boolean?)!!)
            }
            is Float -> {
                return sp.getFloat(key, (defValue as Float?)!!)
            }
            is Int -> {
                return sp.getInt(key, (defValue as Int?)!!)
            }
            is Long -> {
                return sp.getLong(key, (defValue as Long?)!!)
            }
            is String -> {
                return sp.getString(key, defValue as String?)
            }
            else -> return ""
        }
    }

    fun getStringValue(context: Context,key: String,defValue: String):String{
        val sp: SharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        return sp.getString(key,defValue)?:defValue
    }
    fun getBooleanValue(context: Context,key: String,defValue: Boolean):Boolean{
        val sp: SharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        return sp.getBoolean(key,defValue)
    }
    fun getLongValue(context: Context,key: String,defValue: Long):Long{
        val sp: SharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        return sp.getLong(key,defValue)
    }

    fun clearSP(context: Context) {
        context.getSharedPreferences(spName, Context.MODE_PRIVATE)
            .edit()
            .clear()
            .apply()
    }

    fun removeSP(context: Context, Key: String?) {
        context.getSharedPreferences(spName, Context.MODE_PRIVATE)
            .edit()
            .remove(Key)
            .apply()
    }

    fun getAllSP(context: Context): Map<String?, *>? {
        return context.getSharedPreferences(spName, Context.MODE_PRIVATE).getAll()
    }
}